package com.wanlian.dao.impl;

import com.wanlian.common.PageCondition;
import com.wanlian.dao.CardDao;
import com.wanlian.entity.Card;
import com.wanlian.model.ResultModel;
import com.wanlian.util.DateUtil;
import com.wanlian.vo.Page;
import org.hibernate.Session;
import org.hibernate.jdbc.Work;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class CardDaoImpl extends GenericDaoImpl<Card> implements CardDao {

    public CardDaoImpl() {
        super(Card.class);
    }

    @Override
    public ResultModel queryCard(PageCondition pageCondition) {
        ResultModel resultModel = new ResultModel();
        resultModel.setBresult(true);
        StringBuffer sqlWhere = new StringBuffer(" where 1 = 1");
        ArrayList<Object> params = new ArrayList<Object>();

        if (pageCondition.isEmpty("name")) {
            String name = (String) pageCondition.getByKey("name");
            sqlWhere.append(" and name like ?");
            params.add("%" + name + "%");
        }
        if (pageCondition.isEmpty("code")) {
            String code = (String) pageCondition.getByKey("code");
            sqlWhere.append(" and code like ?");
            params.add("%" + code + "%");
        }


        List<Card> lists = new ArrayList<Card>();
        String hql = String.format(" from %s  ", entityClassName(), sqlWhere.toString());
        lists = this.queryForListByPage(hql + sqlWhere, params.toArray(), pageCondition.getPage());
        resultModel.setObject(lists);
        String countHql = String.format("select count(*) from  %s " + sqlWhere, entityClassName(), params.toString());
        Long count = this.queryCount(countHql, params.toArray());
        resultModel.setCount(count);
        return resultModel;
    }

    @Override
    public ResultModel queryCardByUser(Page page, int userId) {
        ResultModel resultModel = new ResultModel();
        resultModel.setBresult(true);
        List<Card> lists = new ArrayList<Card>();
        String hql = String.format("from %s where userid=? order by changetime desc ", entityClassName());
        lists = this.queryForListByPage(hql, new Object[]{userId}, page);
        String counthql = String.format("select count(*) from %s where userid=?", entityClassName());
        Long count = this.queryCount(counthql, new Object[]{userId});
        resultModel.setObject(lists);
        resultModel.setCount(count);
        return resultModel;
    }

    /**
     * 通过code查询卡片
     *
     * @param code
     * @return
     */
    @Override
    public Card queryByCode(String code) {
        String hql = String.format("from %s where code=?", entityClassName());
        Card card = this.queryForObject(hql, new Object[]{code});
        return card;
    }


    @Override
    public Card queryCardByProductId(int id) {
        String hql = String.format(" from %s where productid=? and userid=0 and hasused=0 and isenable=1  ", entityClassName());
        Card card = this.queryForTopObject(hql, new Object[]{id});
        return card;
    }


    @Override
    public long queryCardChanggeTimeById(int userId) {
        String startDate = "";
        String endDate = "";
        try {
            Date dateStart = DateUtil.addDay(DateUtil.currentDate(), 1);
            Date dateNow = DateUtil.currentDate();
            endDate = DateUtil.formatDateNoHour(dateStart);
            startDate = DateUtil.formatDateNoHour(dateNow);
        } catch (Exception e) {
            System.out.println(e);
        }

        String countsql = String.format("select count(*) from %s where   changetime between date(?) and date(?) and userId=? ", entityClassName());
        long count = this.queryCount(countsql, new Object[]{startDate, endDate, userId});
        return count;
    }

    @Override
    public List<Card> queryCardsNoUsed(int id) {
        List<Card> lists = new ArrayList<Card>();
        String hql = String.format("from %s where hasused = ? and productid=? ", entityClassName());
        lists = this.queryForList(hql, new Object[]{false, id});
        return lists;
    }

    @Override
    public void doEditBatch(List<Card> cards) {
        Session session = this.currentSession();
        Work work = new Work() {
            @Override
            public void execute(Connection connection) throws SQLException {
                PreparedStatement stmt = connection.prepareStatement(
                        "INSERT INTO tb_card(productid, ccode, name, upassword, rmb, score,userid, hasused,isEnable,lastTime,changetime,adduserid,imgpath)" +
                                " VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)");
                for (Card card : cards) {
                    stmt.setInt(1, card.getProductId());
                    stmt.setString(2, card.getCode());
                    stmt.setString(3, card.getName());
                    stmt.setString(4, card.getPassword());
                    stmt.setFloat(5, card.getRmb());
                    stmt.setDouble(6, card.getScore());
                    stmt.setInt(7, card.getUserId());
                    stmt.setBoolean(8, card.isHasUsed());
                    stmt.setBoolean(9, card.isEnable());
                    stmt.setTimestamp(10, card.getLastTime());
                    stmt.setTimestamp(11, card.getChangetime());
                    stmt.setInt(12, card.getAddedUserId());
                    stmt.setString(13, card.getImgPath());
                    stmt.addBatch();
                }
                stmt.executeBatch();
            }
        };
        session.doWork(work);
    }
}
